package cn.itcast.exception;

import com.google.common.collect.ImmutableMap;
import cn.itcast.response.ResponseResult;
import cn.itcast.response.StatusCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description:
 * @Version: V1.0
 */
@RestControllerAdvice
public class ExceptionCatch {


    @ExceptionHandler(BusinessException.class) // 拦截是 BusinessException 自定义异常
    public ResponseResult catchBusinessException(BusinessException ex){
        return ex.getResponseResult();
    }

    // 拦截的是不可预知的异常

    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>,ResponseResult> EXCEPTIONS;
    //使用builder来构建一个异常类型和错误代码的异常
    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResponseResult> builder = ImmutableMap.builder();

    @ExceptionHandler(Exception.class)
    public ResponseResult catchExecption(Exception ex){

        // 记日志....

        // 先到 Map 里面找 异常 有 直接返回
        Class<? extends Exception> exClass = ex.getClass();  // 捕获异常类
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }

        ResponseResult responseResult = EXCEPTIONS.get(exClass);
        if (responseResult == null) {
            // 没有 直接返回 99999 您的网络有问题请稍后重试
            return ResponseResult.errorResult(99999, "您的网络有问题请稍后重试");
        }

        return responseResult;

    }


    static {
        // 可以用户自己新增异常类由于更细分异常
        builder.put(ArithmeticException.class, ResponseResult.errorResult(StatusCode.ARITHMETIC_ERROR));
        builder.put(NullPointerException.class, ResponseResult.errorResult(StatusCode.ARITHMETIC_ERROR));
    }
}